<!DOCTYPE html>
<html lang="en" class="no-js" xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/web/thymeleaf/layout" layout:decorator="layout">
<head>
<title>优惠活动管理</title>
</head>
<body>
<div layout:fragment="content">
	<div class="row">
		<div class="col-md-12">
			<div class="btn-group pull-right">
				<a href="index.html" th:href="@{/promotion/activities/index/}" id="sample_editable_1_new" class="btn green">返回<i class="fa fa-arrow-circle-o-left"></i></a>
			</div>
		</div>
	</div>
	<div class="row">
		<div class="col-md-12">
			<div class="form">
				<form role="form" th:action="@{'/promotion/activities/save?page='}+${page}+'&amp;viewState='+${viewState}" th:object="${activities}" id="activitiesForm" method="post" class="form-horizontal">
					<h4 class="form-section">优惠活动信息</h4>
					<input type="hidden" id="activitiesId" th:field="*{id}" />
					<input type="hidden" th:value="${activitiesRangeValue}" id="activitiesRangeValue" name="activitiesRangeValue" />
					<input type="hidden" th:value="${activitiesMethodsValue}" id="activitiesMethodsValue" name="activitiesMethodsValue" />
					<div class="form-body">
						<div class="form-group" th:class="${#fields.hasErrors('activitiesName')}? 'form-group has-error' : 'form-group'">
							<label class="control-label col-md-3">活动名称<span class="required" aria-required="true">* </span></label>							
							<div class="col-md-4">
								<input type="text" class="form-control" placeholder="活动名称" th:field="*{activitiesName}"/>
								<span class="help-block" th:if="${#fields.hasErrors('activitiesName')}" th:errors="*{activitiesName}">活动名称不能为空</span>
							</div>
						</div>
						<div class="form-group" th:class="${#fields.hasErrors('beginTime')}? 'form-group has-error' : 'form-group'">
                            <label class="control-label col-md-3">开始时间<span class="required" aria-required="true">* </span></label>
                            <div class="col-md-4">
                                <input id="text_BeginTime" th:field="*{beginTime}" class="form-control" type="text"></input>
                                <span class="help-block" th:if="${#fields.hasErrors('beginTime')}" th:errors="*{beginTime}">请输入开始时间</span>
                            </div>
						</div>
						
						<div class="form-group" th:class="${#fields.hasErrors('endTime')}? 'form-group has-error' : 'form-group'">
						    <label class="control-label col-md-3">结束时间<span class="required" aria-required="true">* </span></label>
							<div class="col-md-4">
								<input id="text_EndTime" th:field="*{endTime}" data-format="yyyy-MM-dd hh:mm:ss" class="form-control" type="text"></input>
								<span class="help-block" th:if="${#fields.hasErrors('endTime')}" th:errors="*{endTime}">请输入结束时间</span>
							</div>
						</div>

						<div class="form-group">
							<label class="control-label col-md-3">享受优惠会员等级</label>
							<div class="col-md-5">
					            <div class="checkbox-list">
										<label class="checkbox-inline"
											th:each="data : ${userRanks}"> 
												<span><input
													th:field="*{userRankIdList}"   type="checkbox" name="userRankID"
													th:value="${data.id}" th:text="${data.rankName}" id="userRankID"/>
												</span>
									    </label>
								</div>
							</div>
						</div>
						<div class="form-group">
							<label class="control-label col-md-3">优惠范围</label>
							<div class="col-md-4">
								<select th:field="*{activitiesRange}" id="activitiesRange" th:remove="all-but-first" class="form-control" onchange="selectRange(this.value)">
					                <option th:each="type : ${activitiesRange}"
					                        th:value="${type}" th:text="${type.description}"></option>
					            </select> 
							</div>
						</div>
						<div class="form-group" id="brands" style="display:none">
							<label class="control-label col-md-3">优惠品牌<span class="required" aria-required="true">* </span></label>
							<div class="col-md-4">
								<select th:field="*{brands}" th:remove="all-but-first" class="form-control">
					                <option th:each="type : ${brands}"
					                        th:value="${type.id}" th:text="${type.name}"></option>
					            </select> 
							</div>
						</div>
						<div class="form-group" id="categorys" style="display:none">
							<label class="control-label col-md-3">优惠分类</label>
							<div class="col-md-4">
								<select th:field="*{categorysIdList}" th:remove="all-but-first" class="form-control" multiple="multiple">
					                <option th:each="type : ${categorys}"
					                        th:value="${type.id}" th:text="${type.name}"></option>
					            </select> 
							</div>
						</div>
						<div class="row" th:with="selectedGoods=${activities.activitiesGoods},selectableGoods=${selectableGoods}" id="goods" style="display:none">
				            <div class="col-md-12">
					            <div class="form form-inline">
					                <div class="form-group" style="margin:0px">
					                    <select id="goodsCategoryId" name="goodsCategoryId" th:remove="none" class="form-control">
					                        <option value="">所有分类</option>
					                        <option th:each="eachValue : ${categorys}" th:value="${eachValue.id}" th:text="${eachValue.name}"></option>
					                    </select>
					                </div>
					
					                <div class="form-group" style="margin:0px">
					                    <select id="goodsBrandsId" name="goodsBrandsId" th:remove="none" class="form-control">
					                        <option value="">所有品牌</option>
					                        <option th:each="eachValue : ${searchBrands}" th:value="${eachValue.id}" th:text="${eachValue.name}"></option>
					                    </select>
					                </div>
					
					                <div class="form-group" style="margin:0px">
					                    <label class="sr-only" for="goodsName">goodsName</label>
					                    <input type="text" name="goodsName" placeholder="关键词（货号或者名称）"  id="goodsName" class="form-control" />
					                </div>
					 
					                <button type="button" id="bt_search" name="bt_search" class="btn green" onclick="goodsMatchSearch();">
					                    <i class="fa  fa-search"></i>
					                </button>
					            </div>
					        </div>
				            <div class="col-md-12">
				                <div class="form">
				                    <div class="form-body">
				                        <div th:replace="support/searchGoods :: search_list"></div>
				                    </div>
				                </div>
				            </div>
				        </div>
						
						<div class="form-group"  th:class="${#fields.hasErrors('minAmount')}? 'form-group has-error' : 'form-group'">
                            <label class="control-label col-md-3">金额下限<span class="required" aria-required="true">* </span></label>
                            <div class="col-md-4">
                                <input type="text" required="" th:field="*{minAmount}" class="form-control"/>
                                <span class="help-block" th:if="${#fields.hasErrors('minAmount')}" th:errors="*{minAmount}">请输入金额下限</span>
                            </div>
                        </div>
                        <div class="form-group"  th:class="${#fields.hasErrors('maxAmount')}? 'form-group has-error' : 'form-group'">
                            <label class="control-label col-md-3">金额上限<span class="required" aria-required="true">* </span></label>
                            <div class="col-md-4">
                                <input type="text" required="" th:field="*{maxAmount}" class="form-control"/>
                                <span class="help-block" th:if="${#fields.hasErrors('maxAmount')}" th:errors="*{maxAmount}">请输入金额上限</span>
                            </div>
                        </div>
                        
                        <div class="form-group">
							<label class="control-label col-md-3">优惠方式<span class="required" aria-required="true">* </span></label>
							<div class="col-md-6">
								<select th:field="*{activitiesMethods}" th:remove="all-but-first" style="width:200px;float:left;" class="form-control" onchange="selectMethod(this.value)">
					                <option th:each="type : ${activitiesMethods}"
					                        th:value="${type}" th:text="${type.description}"></option>
					            </select>
					            <input type="text" required="" th:field="*{methodsExt}" id="methodsExt" value="0" style="width:100px;padding-left:10px;" class="form-control"/>
					            当优惠方式为“满购/满赠”时，请输入允许买家选择赠品（特惠品）的最大数量，数量为0表示不限数量；当优惠方式为“满减”时，请输入现金减免的金额；当优惠方式为“满折”时，请输入折扣（1－99），如：打9折，就输入90。
							</div>
						</div>
						<div class="row" id="methodbuygive" style="display:none">
						    <div class="col-md-12">
					            <div class="form form-inline" style="margin-bottom:10px;">
					                <div class="form-group" style="margin:0px">
					                    <select id="goodsCategoryId1" name="goodsCategoryId1" th:remove="none" class="form-control">
					                        <option value="">所有分类</option>
					                        <option th:each="eachValue : ${categorys}" th:value="${eachValue.id}" th:text="${eachValue.name}"></option>
					                    </select>
					                </div>
					
					                <div class="form-group" style="margin:0px">
					                    <select id="goodsBrandsId1" name="goodsBrandsId1" th:remove="none" class="form-control">
					                        <option value="">所有品牌</option>
					                        <option th:each="eachValue : ${brands}" th:value="${eachValue.id}" th:text="${eachValue.name}"></option>
					                    </select>
					                </div>
					
					                <div class="form-group" style="margin:0px">
					                    <label class="sr-only" for="goodsName">goodsName</label>
					                    <input type="text" name="goodsName1" placeholder="商品名称"  id="goodsName1" class="form-control" />
					                </div>
					                <button type="button" id="bt_search" name="bt_search" class="btn green" onclick="buygiveGoodsSearch();">
					                    <i class="fa  fa-search"></i>
					                </button>
					            </div>
					        </div>
					        <div class="form-group">
								<label class="control-label col-md-3">满购满赠商品</label>
								<div class="col-md-8">
									<select id="buygivegoods" name="buygivegoods" style="width:400px;float:left;" class="form-control">
							                <option value="0">请选择满购满赠商品</option>
							         </select>
						      		 <a class="btn green" href="javascript:void(0)" onclick="addgood();">
									 <i class="fa fa-plus"></i>
									 </a>
								</div>
							</div>
							<div class="form-group">
								<label class="control-label col-md-3"></label>
								<div class="col-md-6">
									<table id="tab">
										<tr th:each="data : ${activities.methodsGoods}" th:id="${dataStat.index}" align='center'>
										<input type="hidden" th:attr="id=${'id'+dataStat.index},name=${'id'+dataStat.index}" th:value="${data.key.id}" size='4' />
										<input type="hidden" th:attr="id=${'name'+dataStat.index},name=${'name'+dataStat.index}" th:value="${data.key.name}" size='4' />
										<td width='400px' th:text="${data.key.name}"></td>
										<td width='80px'><input type='text' th:attr="id=${'price'+dataStat.index},name=${'price'+dataStat.index}" th:value='${data.value}' size='5' />元</td>
										<td width='50px'><a href='javascript:void(0)' onclick="deltr(this)" >删除</a></td>
	                                    </tr>
									</table>
								</div>
							</div>
							
					      </div>
						
					</div>
					<div class="form-actions fluid">
						<div class="col-md-offset-3 col-md-9">
<!-- 							<button id="btn_form_submit" onlick="checkAndSubmit()" class="btn blue">提交</button> -->
							<input type="button" onclick="check()" class="btn blue" value="提交" />
						</div>
					</div>
					<input type="hidden" th:field="*{activitiesGoodsids}" id="activitiesGoodsids" />
					<input type="hidden" th:field="*{methodsGoodsids}" id="methodsGoodsids" />
				</form>		
			</div>
		</div>
	</div>

	
    

</div>	
</body>
</html>
 <script th:inline="javascript">
	/*<![CDATA[*/
          jQuery.validator.addMethod("checkMaxAmount", function(value, element) { 
			var minAmount = $("#minAmount").val();
			var maxAmount = $("#maxAmount").val();
			if(value == 0) {
				return true;
			}

			return this.optional(element) || (value-minAmount)>0 ;  
		}, "金额上限不能低于等于金额下限");
	
          jQuery.validator.addMethod("checkMethodsExt", function(value, element) { 
  			var methodsExt = $("#methodsExt").val();
  			var _activitiesMethods = $("#activitiesMethods").val();
  			if(_activitiesMethods != "DISCOUNT") {
  				return true;
  			}

  			return this.optional(element) || methodsExt>0 && methodsExt<100 ;  
  		}, "折扣范围为1-99");
	    //页面加载执行
	    $(document).ready(function() { 
			var _activitiesRangeValue = $("#activitiesRangeValue").val();
			var _activitiesMethodsValue = $("#activitiesMethodsValue").val();
			if(_activitiesRangeValue=="CATBRAND"){
				$("#brands").show();
				$("#categorys").show();
			}else if(_activitiesRangeValue=="GOODS"){
				$("#goods").show();
			}
			if(_activitiesMethodsValue=="BUYGIVE"){
				$("#methodbuygive").show();
			}
			
			$("#activitiesForm").validate({
	            rules:{
	            	activitiesName:{
	                    required:true,
	                    maxlength:100
	                },
	                userRankIdList:{
	                	  required:true
	                  },
	                minAmount:{
	                	required:true,
	                    min:0,
	                    max:99999999.99,
	                    number:true
	                },
	                maxAmount:{
	                	required:true,
	                    min:0,
	                    max:99999999.99,
	                    checkMaxAmount:true,
	                    number:true
	                },
	                methodsExt:{
	                	required:true,
	                	checkMethodsExt:true,
	                    min:0,
	                    max:99999999.99,
	                    number:true
	                },
	                beginTime:{
	                    required:true
	                },
	                endTime:{
	                    required:true
	                }
	            },
	            messages:{
	            	activitiesName:{
	                    required:'请输入促销活动名称',
	                    maxlength:"促销活动名称不可超过100"
	                },
	                userRankIdList:{
	                	required:"请选择享受优惠会员等级"
	                },
	                minAmount:{
	                    required:'请输入金额下限',
	                    min:'金额下限最小值为0且必须为数字',
	                    max:'金额下限最大值为99999999.99且必须为数字',
	                    number:'请输入正确的金额下限'
	                },
	                maxAmount:{
	                    required:'请输入金额上限',
	                    min:'金额上限最小值为0且必须为数字',
	                    max:'金额上限最大值为99999999.99且必须为数字',
	                    number:'请输入正确的金额上限'
	                },
	                methodsExt:{
	                    required:'请输入优惠方式后的数值',
	                    min:'最小值为0且必须为数字',
	                    max:'最大值为99999999.99且必须为数字',
	                    number:'请输入正确的优惠方式后的数值'
	                },
	                beginTime:{
	                    required:'请输入开始时间'
	                },
	                endTime:{
	                    required:'请输入结束时间'
	                }
	            }
	        });
		});
	
	    function check(){
	        var startTime=$("#text_BeginTime").val();
	        var start=new Date(startTime.replace("-", "/").replace("-", "/"));
	        var endTime=$("#text_EndTime").val();
	        var end=new Date(endTime.replace("-", "/").replace("-", "/"));
	        if(end <= start){
	            alert("开始时间要小于结束时间");
	            return  false;
	        }
	        var _activitiesRange = $("#activitiesRange").val();
	        var _activitiesMethods = $("#activitiesMethods").val();
	        $('#activitiesGoodsids').val(getSelectedGoodsIds());
	        $('#methodsGoodsids').val(getBuygiveGoodsIds());
	        if($('#methodsGoodsids').val()==0 && _activitiesMethods=="BUYGIVE"){
	        	alert("请输入正确的满购/满赠商品的价格,价格不能超过999999999");
	        	return false;
	        }
	        if(!$('#activitiesGoodsids').val() && _activitiesRange=="GOODS"){
	            alert("请选择优惠范围内的商品");
	            return  false;
	        }else if($('#brands option:selected').val()==0 && _activitiesRange=="CATBRAND"){
	        	alert("请选择优惠品牌");
	            return  false;
	        }
	        if(!$('#methodsGoodsids').val() && _activitiesMethods=="BUYGIVE"){
	            alert("请选择满购/满赠的商品");
	            return  false;
	        }
	        //console.info($('#form_combo_edit').serialize());
	        //return false;
	        //$('#btn_form_submit').click();
	        $('#activitiesForm').submit();
	    }
	
		$("#text_BeginTime").click(function(){
			WdatePicker({startDate:'%y-%M-01 00:00:00',dateFmt:'yyyy-MM-dd HH:mm:ss',alwaysUseStartDate:true,readOnly:true});
		}).focus(function () {
            WdatePicker({startDate:'%y-%M-01 00:00:00',dateFmt:'yyyy-MM-dd HH:mm:ss',alwaysUseStartDate:true,readOnly:true});
        });
		$("#text_EndTime").click(function(){
			WdatePicker({startDate:'%y-%M-01 00:00:00',dateFmt:'yyyy-MM-dd HH:mm:ss',alwaysUseStartDate:true,readOnly:true});
		}).focus(function () {
            WdatePicker({startDate:'%y-%M-01 00:00:00',dateFmt:'yyyy-MM-dd HH:mm:ss',alwaysUseStartDate:true,readOnly:true});
        });
		
		
		
		
		function selectRange(value){
			if(value=="CATBRAND"){
				$("#brands").show();
				$("#categorys").show();
				$("#goods").hide();
			}else if(value=="GOODS"){
				$("#brands").hide();
				$("#categorys").hide();
				$("#goods").show();
			}else{
				$("#brands").hide();
				$("#categorys").hide();
				$("#goods").hide();
			}
		}
		
		function selectMethod(value){
			if(value=="BUYGIVE"){
				$("#methodbuygive").show();
			}else{
				$("#methodbuygive").hide();
			}
		}
		
		function addgood(){
			var _id = $("#buygivegoods").val();
			var _name = $("#buygivegoods option:selected").text();
			var _len = $("#tab tr").length;
			if(_id==0){
				alert("请先选择一个商品");return;
			}
			for(var i=0,j=_len;i<j;i++){
				if(_id==$("#id"+i).val()){
					alert("该商品已经添加");return;
				}
			}
			$("#tab").append("<tr id="+_len+" align='center'>"
					+"<input type='hidden' name='id"+_len+"' id='id"+_len+"' value="+_id+" size='4' />"
					+"<input type='hidden' name='name"+_len+"' id='name"+_len+"' value="+_name+" size='4' />"
					+"<td width='400px'>"+_name+"</td>"
					+"<td width='80px'><input type='text' name='price"+_len+"' id='price"+_len+"' value='0' size='5' />元</td>"
					+"<td width='50px'><a href=\'javascript:void(0)\' onclick=\'deltr(this)\'>删除</a></td>"
					+"</tr>");   
		}
		
		//删除<tr/>
		var deltr =function(node)
		{
	        $(node).parent().parent().remove();
        }
		
		function getBuygiveGoodsIds(){
			var buygiveGoodsIds = '';
			var _len = $("#tab tr").length;
			var re = /^[0-9]+.?[0-9]*$/;
			if(_len != 0){
				for(var i=0,j=_len;i<j;i++){
					var gid = $("#id"+i).val();
					var gprice = $("#price"+i).val();
					var matchprice = Math.round(gprice);
					if(gprice=='' || !re.test(gprice) || matchprice>999999999){
						buygiveGoodsIds=0;
						return buygiveGoodsIds;
					}
					buygiveGoodsIds += gid+','+gprice;
					buygiveGoodsIds += ';';
				}
				if(buygiveGoodsIds.length > 0){
					buygiveGoodsIds = buygiveGoodsIds.slice(0,-1);
		        }
			}
			return buygiveGoodsIds;
			
		}
		
		function getMatchedGoodsIds(){
	        var matchedGoodsId = '';
	        $('#select_matchedList').children().each(function(){
	            matchedGoodsId += this.value;
	            matchedGoodsId += ',';
	        });
	        if(matchedGoodsId.length > 0){
	            matchedGoodsId = matchedGoodsId.slice(0,-1);
	        }
	        return matchedGoodsId;
	    }

	    function goodsMatchSearch(){
	    	var _goodsCategoryId = $("#goodsCategoryId").val();
	        var _goodsBrandsId = $("#goodsBrandsId").val();
	        var _goodsName = $("#goodsName").val();
	        var _searchType = "ACTIVITIES";
	        var _searchId = $("#activitiesId").val()?$("#activitiesId").val():0;
	        var _matchedIds = getSelectedGoodsIds();
            $.ajax({
                url:'/goods/goods/selectableGoods',
                data:{categoryId:_goodsCategoryId,brandId:_goodsBrandsId,goodsName:_goodsName,searchType:_searchType,searchId:_searchId,excludGoodsIds:_matchedIds},
                //data:$('#form_goods_search').serialize()+'&excludGoodsIds='+getSelectedGoodsIds(),
                type:'post',
                async:false,
                dataType:'json',
                success:function(data){
                    $('#select_matchable_goodsList').empty();
                    if(data.length){
                        for(var i =0 ;i<data.length;i++){
                            $('#select_matchable_goodsList').append('<option value="'+data[i].id+'">'+data[i].name+'</option>');
                        }
                    }
                },
                error:function(XMLHttpRequest, textStatus, errorThrown){

                }
            });
        }
	    
	    //满购满赠商品搜索
	    function buygiveGoodsSearch(){
	    	var _goodsCategoryId = $("#goodsCategoryId1").val();
	        var _goodsBrandsId = $("#goodsBrandsId1").val();
	        var _goodsName = $("#goodsName1").val();
	        $.ajax({
	            url:'/promotion/activities/buygeiveGoodsSearch',
	            data:{goodsCategoryId:_goodsCategoryId,goodsBrandsId:_goodsBrandsId,goodsName:_goodsName},
	            type:'post',
	            async:false,
	            dataType:'json',
	            success:function(data){
	                $('#buygivegoods').empty();
	                if(data.length){
	                    for(var i =0 ;i<data.length;i++){
	                        $('#buygivegoods').append('<option value="'+data[i].id+'">'+data[i].name+'</option>');
	                    }
	                }
	            },
	            error:function(XMLHttpRequest, textStatus, errorThrown){

	            }
	        });
	    }

	
	    
	    
	           
	/*]]>*/
</script>